import { lwarn } from "../logger/Logger";

export default class Config {
    private static _config: object = {};

    /**
     * 初始化配置(使用一个对象来初始化配置)
     * @param data 配置数据
     * @returns null
     */
    public static Init(data: object = {}) {
        this._config = data;
    }

    /**
     * 设置配置
     * @param key 配置key(使用.来区分层级)
     * @param value 配置值
     */
    public static Set(key: string, value: any) {
        const keys = key.split('.')
        if (keys.length == 1) {
            this._config[key] = value;
            return;
        }

        let curConfig = this._config;
        for (let i = 0; i < keys.length - 1; i++) {
            if (typeof curConfig !== 'object') {
                lwarn(`父级配置不是对象, 父级: ${keys.slice(0, i).join('.')}, 当前级: ${keys[i]}`);
                return;
            }

            const curKey = keys[i]
            if(curConfig[curKey] === undefined) {
                curConfig[curKey] = {}
            }

            curConfig = curConfig[curKey];
        }

        curConfig[keys[keys.length - 1]] = value;
    }

    /**
     * 获取配置值
     * @param key 配置key(使用.来区分层级)
     * @returns 配置值
     */
    public static Get(key: string = null, defautlVal: any = undefined): any {
        if(key === null) {
            return this._config;
        }

        const keys = key.split('.')
        if (keys.length == 1) {
            return this._config[key];
        }

        let result = this._config;
        for (let i = 0; i < keys.length; i++) {
            if (typeof result !== 'object') {
                return defautlVal;
            }

            result = result[keys[i]];
        }

        return result === undefined ? defautlVal : result;
    }

    public static Delete(key: string) {
        const keys = key.split('.')
        if (keys.length == 1) {
            delete this._config[key];
            return;
        }

        let curConfig = this._config;
        for (let i = 0; i < keys.length - 1; i++) {
            if (typeof curConfig !== 'object') {
                lwarn(`没有找到父级配置, 父级: ${keys.slice(0, i - 1)}, 当前: ${keys[i]}`);
                return;
            }

            curConfig = curConfig[keys[i]];
        }

        delete curConfig[keys[keys.length - 1]];
    }
}

// 快捷函数
export function config_get(key: string = null, defaultVal: any = undefined): any {
    return Config.Get(key, defaultVal);
}

export function config_set(key: string, value: any) {
    Config.Set(key, value);
}

export function config_del(key: string) {
    Config.Delete(key);
}